import { Button, Drawer, Flex, Form, Input } from "antd";
import { forwardRef, useImperativeHandle, useState } from "react";
import { setToken, type DataItem } from "./api";

interface UpdateDrawerProps {
  onOk: () => void
}

export default forwardRef(function UpdateDrawer(props: UpdateDrawerProps, ref) {
  const { onOk } = props
  const [open, setOpen] = useState<boolean>(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [$form] = Form.useForm();

  const init = (data: DataItem) => {
    $form.setFieldsValue(data)
    setIsEdit(true)
  }
  const handleOpen = (data: DataItem) => {
    setOpen(true);
    if (data) {
      init(data)
    }
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleOk = async () => {
    const values = await $form.validateFields();
    console.log(values);
    await setToken({ ...values, tokenDate: new Date().toISOString() });
    handleClose();
    onOk()
  }

  useImperativeHandle(ref, () => ({
    open: handleOpen,
    close: handleClose,
  }));


  return <Drawer
    title="新增Token"
    onClose={handleClose}
    open={open}
    afterOpenChange={(open) => {
      if (!open) {
        $form.resetFields();
      }
    }}
    footer={<Flex gap={8} justify="end">
      <Button onClick={handleClose}>取消</Button>
      <Button type="primary" onClick={handleOk}>确认</Button>
    </Flex>}
  >
    <Form form={$form} labelCol={{ span: 5 }}
    >
      <Form.Item
        label="姓名"
        name="realName"
        required
        rules={[{ required: true, message: '请输入' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="域账号"
        name="userName"
        required
        rules={[{ required: true, message: '请输入' }]}
      >
        <Input disabled={isEdit}/>
      </Form.Item>

      <Form.Item
        label="token"
        name="token"
        required
        rules={[{ required: true, message: '请输入' }]}
      >
        <Input.TextArea />
      </Form.Item>
    </Form>
  </Drawer>
})